import axios from 'axios'
import {getStore} from '@/config/global'
import { Dialog, Toast } from 'vant';
import router from '../router/index'
import {loginWxAuthorize} from '@/utils/utils'

import store from '@/store'
import {removeStore} from "../config/global";

console.log('baseurl' + process.env.VUE_APP_BASEURL);

// create an axios instance
const service = axios.create({
    // baseURL: "https://ktwy.pmssaas.com/api",
    // baseURL:  "http://47.103.219.130:8080",
    // baseURL:  "/api",

    baseURL:process.env.VUE_APP_BASEURL,

    withCredentials : true,

    // baseURL:  "http://192.168.8.105:8080",
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
    // headers : post['Content-Type'] = 'application/json',
})

// request interceptor
service.interceptors.request.use(
  config => {

      config.headers['Access-Control-Allow-Origin'] = '*';

      // do something before request is sent
      let userInfo = JSON.parse(getStore('userInfo'));

      if(userInfo){
          config.headers['Authorization'] =  'Bearer ' + userInfo.jwt;
      }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
      Toast.clear();
    const res = response.data
      // console.log(response.config.url);
      // console.log("code : = " + res.code + "  message : = " + res.message);

      // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {


      //   Message({
      //   message: res.message || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })


      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401) {
          if(response.config.url !== '/api/home/order' && response.config.url !== '/home/order'){
              Toast('登录过期,请重新登录');


              store.state.userInfo = {};
              removeStore('userInfo');


              loginWxAuthorize();
              // router.push({path:'/login'});
          }
      }

        return Promise.reject(new Error(res.message || 'Error'))
    } else {

        return res
    }
  },
  error => {
     console.log('err' + error) // for debug

      Toast.fail(error.message + '---');

      return Promise.reject(error)
  }
)

export default service
